package me.hunche.app.sms;

import java.util.List;

import me.hunche.app.dao.ActivityDao;
import me.hunche.app.dao.UserDao;
import me.hunche.app.domain.Activity;
import me.hunche.app.domain.User;
import me.hunche.app.exception.UserJoinedException;
import me.hunche.app.service.CoreService;
import me.hunche.app.service.NotifyService;
import me.hunche.app.service.SMSService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("BMHandler")
public class BMHandler implements SMSHandler,InitializingBean{
	
	private static final String prefix ="BM";
	private static final Logger logger = Logger.getLogger(BMHandler.class);
	
	@Autowired ActivityDao activityDao;
	@Autowired CoreService coreService;
	@Autowired UserDao userDao;
	@Autowired NotifyService notifyService;
	

	@Autowired SMSService smsService;

	public String getPrefix() {
		return prefix;
	}
	
	public void afterPropertiesSet() throws Exception {
		
		logger.info("initialize");
		smsService.registerHandler(this);
	}

	public boolean execute(String mobile, String content) {
		if(logger.isDebugEnabled()){
			logger.debug("execute("+mobile +" "+ content+ ") - start");
		}
		
		User user  = userDao.findByMobile(mobile);
		List<Activity> as = activityDao.findByStatusAndTeamId(Activity.STATUS_RECRUIT,user.getTeamId());
		//TODO 同时多个活动召集
		if(as!=null && !as.isEmpty()){
			try {
				Activity a = coreService.joinActivity(user, as.get(0).getId(),true);
//				notifyService.result(a,user);
			} catch (UserJoinedException e) {
				logger.info("User "+user.getUsername() +" repeat registration!");
			} catch (Exception e1){
				logger.error(e1.getMessage());
				e1.printStackTrace();
			}
			
		}else{
			logger.error("no recruit activity");
		}
		
		if(logger.isInfoEnabled()){
			logger.info("execute("+mobile +" "+ content+ " - end");
		}
		return true;
	}
}
